package com.sinping.qh.api.auth;


import com.sinping.qh.api.admin.base.BaseAdminEndPoint;
import com.sinping.qh.api.exception.HandlerException;
import com.sinping.qh.api.filter.AuthFilter;
import com.sinping.qh.api.support.Const;
import com.sinping.qh.api.support.ConstEum;
import com.sinping.qh.api.support.ResDto;
import com.sinping.qh.domain.auth.Token;
import com.sinping.qh.domain.auth.User;
import com.sinping.qh.dto.auth.UserSessionDTO;
import com.sinping.qh.repository.mongo.user.UserLaboratoryRepository;
import com.sinping.qh.service.auth.ISessionService;
import com.sinping.qh.service.auth.ITokenService;
import com.sinping.qh.service.auth.IUserService;
import com.sinping.qh.utils.ip.IPUtils;
import com.sinping.qh.utils.mapper.JsonMapper;
import com.sinping.qh.utils.misc.IdGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 杨云博
 * @since 2017-12-21
 */
@RestController
@Api(value = "admin用户登录", description = "admin用户登录API")
@RequestMapping(value = Const.BASE_URI, name = "登录退出")
public class TokenEndPoint extends BaseAdminEndPoint {

    private final static Logger log = LoggerFactory.getLogger(TokenEndPoint.class);

    @Autowired
    @SuppressWarnings("SpringJavaAutowiringInspection")
    private ISessionService sessionService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ITokenService tokenService;
    @Autowired
    UserLaboratoryRepository userLaboratoryRepository;

    @ApiOperation(httpMethod = "POST", value = "用户登录")
    @RequestMapping(value = "admin_login", name = "用户登录", method = RequestMethod.POST)
    public ResDto login(@ApiParam(name = "msg", value = "{\"password\":\"000000\",\"user_name\":\"admin\"}") @RequestParam(required = true) String msg,
                        HttpServletRequest request) {

        User user = JsonMapper.defaultMapper().fromJson(msg, User.class);
        if(user == null){
            log.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "msg.param.error");
        }

        ResDto resDto = new ResDto();
        if (user.getContent() != null && user.getUsername() != null && !"".equals(user.getContent().trim()) && !"".equals(user.getUsername().trim())) {

            log.info("用户登录校验开始");
            User validateUserLogin = userService.validateUserLogin(user);
            if (validateUserLogin != null) {
                log.info("用户登录校验成功");

                String uuid2 = "";
                Token get = tokenService.getTokenByUserId(validateUserLogin.getId());
                if (get != null) {
                    uuid2 = get.getToken();
                } else {
                    uuid2 = IdGenerator.uuid2();
                }


                log.info("构建登录用户权限");
                UserSessionDTO sessionByToken = sessionService.createSessionByToken(uuid2, validateUserLogin);

                if(sessionByToken.getUrlResoure().size()==0){
                    throw  new HandlerException(ConstEum.FAIL,"请联系管理配置权限");
                }

                log.info("开始存入redis");
                int i = sessionService.saveSessionToRedis(sessionByToken);

                log.info("开始构建token对象");
                Token token = new Token();
                token.setId(get == null ? IdGenerator.uuid2() : get.getId());
                token.setToken(uuid2);
//                if (get == null) {
//                    token.setPassLoginTimes(1);
//                } else {
//                    if (get.getPassLoginTimes() == null) {
//                        token.setPassLoginTimes(1);
//                    } else {
//                        token.setPassLoginTimes(new Integer(get.getPassLoginTimes()) + 1);
//                    }
//                }
                token.setUserId(validateUserLogin.getId());
                token.setDevice(1);
                token.setNickName(validateUserLogin.getNickname());
                token.setVersion("1");
                token.setUserName(validateUserLogin.getUsername());
                token.setIp(IPUtils.getIpAddr(request));
                if (get == null) {
                    token.setCreateTime(new Date());
                }
                token.setUpdateTime(new Date());

                log.info("保存或更新token对象到数据库中");
                tokenService.insertOrUpdate(token);

                resDto.setStatus(Const.SUCCESS);
                HashMap<String, String> stringStringHashMap = new HashMap<>();
                stringStringHashMap.put(AuthFilter.token_name, uuid2);
                String resultStr = JsonMapper.defaultMapper().toJson(stringStringHashMap);
                resDto.setDatas(resultStr);
//                log.info("最后返回值 {}", resultStr);
                return resDto;

            } else {
                log.error("用户名或密码错误");
                resDto.setStatus(Const.DATA_ERROR);
                resDto.setMsg("用户名或密码错误");
                return resDto;
            }

        } else {
            log.error("用户名和密码不能为空");
            resDto.setStatus(Const.PARAM_ERROR);
            resDto.setMsg("msg.param.error");
            return resDto;
        }
    }

    @ApiOperation(value = "登出用户")
    @RequestMapping( value = "admin_logout", name = "登出用户", method = RequestMethod.POST)
    public ResDto logout(ServletRequest httpServlet) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) httpServlet;
        String token = httpServletRequest.getHeader("token");
        ResDto resDto = new ResDto(Const.PARAM_ERROR, "msg.param.error");
        if (StringUtils.isNotBlank(token)) {
            try {
                Long aLong = sessionService.deleteSessionByToken(token);
                if (aLong == 1) {
                    resDto.setStatus(Const.SUCCESS);
                    resDto.setMsg("msg.handle.success");
                } else {
                    resDto.setMsg("msg.handle.fail");
                }
            } catch (Exception e) {
                log.error("踢出用户异常", e);
                resDto.setMsg("msg.handle.fail");
            }
        }
        return resDto;
    }

}

